<template>
  <el-dialog v-model="accountStore.showLoginForm" :title="options.title" :close-on-click-modal="false"
    @close="handleCancel" width="30%" center append-to-body draggable>
    <el-form :ref="options.ref" :model="loginModel" :rules="options.rules" class="login-form">
      <el-form-item prop="username">
        <el-input v-model="loginModel.username" type="text" size="large" auto-complete="off" placeholder="请输入用户名">
          <template #prefix>
            <el-icon :size="20">
              <User />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input v-model="loginModel.password" type="password" size="large" auto-complete="off" placeholder="请输入密码">
          <template #prefix>
            <el-icon :size="20">
              <Lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleLogin" auto-insert-space>
          <span v-if="!loading">登录</span>
          <span v-else>登录...</span>
        </el-button>
        <el-button @click="handleCancel" auto-insert-space>取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="LoginConfirm">
import { ref, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { useAccountStore } from '@/store/account'
import { encrypt } from '@/utils/jsencrypt'
import _ from 'lodash'

// import settings from '@/settings'

const options = {
  ref: 'loginRef',
  title: '登录已过期,请重新登录!',
  action: undefined,
  rules: []
}

const loginModel = ref({
  username: 'admin',
  password: '123456'
})

const loading = ref(false)
const { proxy } = getCurrentInstance()
const router = useRouter()
const accountStore = useAccountStore()

function handleLogin() {
  proxy.$refs[options.ref].validate((valid) => {
    if (valid) {
      const data = _.cloneDeep(loginModel.value)
      // 密码加密
      data.password = encrypt(data.password)
      // 登录请求
      loading.value = true
      accountStore
        .Login(data)
        .then((res) => {
          //   router.push({ path: '/' })
          accountStore.setShowLoginForm(false)
          loading.value = false
        })
        .catch((e) => {
          console.log(e)
          loading.value = false
        })
    }
  })
}

function handleCancel() {
  accountStore.setShowLoginForm(false)
}
</script>

<style lang="scss" scoped>

</style>
